import Dao from "../../utils/dao";
import {getLocal, setLocal} from "../../utils/local";

export async function addShop(_shopData) {
    var shopData = {..._shopData}
    var shopDao = new Dao('shop')
    var userDao = new Dao('user')
    var user = getLocal('app.login_user')
    var selectResult = await  shopDao.selectOne({name: shopData.name})
    /*可以增加*/
    if (!selectResult) {
        var imageCreateWithoutData = AV.File.createWithoutData(shopData.image.objectId);
        shopData.image = imageCreateWithoutData
        var userCreateWithoutData = AV.Object.createWithoutData('user', user.objectId);
        var addShopResult = (await shopDao.insert({...shopData, user: userCreateWithoutData})).toJSON()

        var shopCreateWithoutData = AV.Object.createWithoutData('shop', addShopResult.objectId);
        var updateUserResult = (await userDao.update(user.objectId, {defaultShop: shopCreateWithoutData})).toJSON()
        setLocal("app.login_user", {
            ...getLocal("app.login_user"),
            ...updateUserResult
        })
        return addShopResult
    } else {
        return Promise.reject({message: "店铺名字已经被使用"})
    }
}